package net.net23.sysdent.server.services;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.net23.sysdent.client.services.LinksService;
import net.net23.sysdent.server.jdo.control.LinkController;
import net.net23.sysdent.server.jdo.control.UserController;
import net.net23.sysdent.server.jdo.pojos.User;
import net.net23.sysdent.shared.jto.Link;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class LinksServiceImp extends RemoteServiceServlet implements
		LinksService {

	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd");

	@Override
	public List<Link> search(String filters) {
		UserService userService = UserServiceFactory.getUserService();
		String email = userService.getCurrentUser().getEmail();
		User user = UserController.forceUserByMail(email);
		List<net.net23.sysdent.server.jdo.pojos.Link> links = LinkController
				.getLinksByUser(filters, user.getId(), 0, -1);

		List<Link> _links = new ArrayList<Link>();
		if (links != null) {
			for (net.net23.sysdent.server.jdo.pojos.Link link : links) {
				Link _link = new Link(link.getLink(), link.getUser());
				_link.setId( link.getId() );
				boolean hasName = link.getName() != null
						&& link.getName().trim().length() > 0;
				_link.setName(hasName ? link.getName() : link.getLink());
				_link.setCreationDate(link.getCreationDate());
				_link.setShortCreationDate(sdf.format(link.getCreationDate()));
				Set<String> kw = new HashSet<String>();
				kw.addAll(link.getKeyWords());
				_link.setKeyWords( kw );
				_links.add(_link);
			}
		}
		return _links;
	}

	@Override
	public void create(Link link) throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		String email = userService.getCurrentUser().getEmail();
		User user = UserController.forceUserByMail(email);
		LinkController.forceByUser(user, link);
		link.setUser(user.getId());
	}

	@Override
	public void update(Link link) throws Exception {
		LinkController.update(link);
	}
}
